import sys
import openai
import pymysql
import json
import os

os.environ["http_proxy"] = "http://localhost:7890"
os.environ["https_proxy"] = "http://localhost:7890"
# def get_chat_messages(prompt_text):
#     openai.api_key = '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'
#     response = openai.ChatCompletion.create(
#         model="gpt-3.5-turbo",
#         messages=prompt_text,
#         max_tokens=2000,
#         n=1,
#         stop=None,
#         temperature=0.5,
#     )
#     return response.choices[0].message.content

# 单轮对话调用
# model可选"gpt-3.5-turbo"与"gpt-3.5-turbo-0301"


def generate_answer(messages):
    completion = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages,
        temperature=0.7
    )
    res_msg = completion.choices[0].message
    return res_msg["content"].strip()


def messages2str(messages):
    re = ''
    for dict in messages:
        re += "&" + dict['role'] + "&" + dict['content']
    return re[1:]


def str2messages(str):
    li = str.split('&')
    i = 0
    messages = []
    while i < len(li):
        messages.append({'role': li[i], 'content': li[i+1]})
        i += 2
    return messages


openai.api_key = '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'

conn = pymysql.connect(host='62.234.21.39', port=3306,
                       user='root', passwd='Z36576', charset="utf8", db='elm')
cursor = conn.cursor()
sql = "select businessName, businessId from business"
cursor.execute(sql)

results = cursor.fetchall()
business_infos = [result for result in results]

business_ids = [result[1] for result in results]
business_names = [result[0].split('（')[0] for result in results]

foods = []
for business_id in business_ids:
    sql = f"select foodName from food where businessId = {business_id}"
    cursor.execute(sql)
    results = cursor.fetchall()
    food = [result[0] for result in results]
    foods.append(food)

food_set = ''
for b, f in zip(business_names, foods):
    s = f'{b}: ' + '、'.join(f)
    food_set += s + '\n'


if len(sys.argv) == 2:
    chat = False
    question = sys.argv[1]
else:
    chat = True
    question = sys.argv[1]
    conversation_id = sys.argv[2]

if chat:
    if conversation_id == 'None':
        prompt_text = {
            "role": "system", "content": "已知这些商家有这些食品正在销售。你将扮演一个点餐服务员，要询问顾客今天想吃的什么（记住你是一个服务员！）" + food_set + "。"}
        messages = [prompt_text]
        messages.append({"role": "user", "content": '你好'})
        messages.append({"role": "assistant", "content": '您好，请问您今天想吃什么？'})
        prompt = question
        messages.append({"role": "user", "content": prompt})
        res_msg = generate_answer(messages)
        messages.append({"role": "assistant", "content": res_msg})
        sql = f'select count(*) from chatHistory'
        cursor.execute(sql)
        conversation_id = cursor.fetchall()[0][0]
        messages_str = messages2str(messages)
        sql = f"insert into chatHistory values ({conversation_id}, \"{messages_str}\")"
        if cursor.execute(sql) != 0:
            conn.commit()
            # print('insert')
        results = cursor.fetchall()
        print(res_msg + '&' + str(conversation_id))

    else:
        sql = f'select str from chatHistory where conversation_id = {conversation_id}'
        cursor.execute(sql)
        history = cursor.fetchall()[0][0]
        messages = str2messages(history)
        messages.append({"role": "user", "content": question})
        res_msg = generate_answer(messages)
        messages.append({"role": "assistant", "content": res_msg})
        messages_str = messages2str(messages)
        sql = f"update chatHistory set str=\"{messages_str}\" where conversation_id = {conversation_id}"
        if cursor.execute(sql) != 0:
            conn.commit()
            # print('update')

        print(res_msg + '&' + str(conversation_id))

else:
    preference = question
    prompt_text = [{"role": "system", "content": "已知这些商家有这些食品正在销售。你将扮演一个点餐服务员，要询问顾客今天想吃的什么（记住你是一个服务员！）" + food_set + "。"},
                   {"role": "user", "content": "我的口味偏好是“" + preference + "”，给我推荐3种菜，列，格式参考：1、菜名 - 商家\n2、菜名 - 商家"}]

    # 调用ChatGPT API生成回复
    response_content = generate_answer(prompt_text)

    response_content = "\n".join(
        [line for line in response_content.split("\n") if line[0].isdigit()])

    # 打印生成的回复
    print(response_content)

cursor.close()
conn.close()
